<?php

namespace plugin\property\app\model;

use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Support\Str;
use plugin\enterprise\app\Enterprise;
use plugin\owladmin\app\Admin;
use plugin\owladmin\app\model\AdminMenu;
use support\Request;

class PropertyPermission extends \plugin\owladmin\app\model\AdminPermission
{
    protected $table = 'property_admin_permissions';


    public function menus(): BelongsToMany
    {
        return $this->belongsToMany(PropertyMenu::class, 'property_admin_permission_menu', 'permission_id', 'menu_id')
            ->withTimestamps();
    }

    public function shouldPassThrough(Request $request): bool
    {
        if (empty($this->http_method) && empty($this->http_path)) {
            return true;
        }
        $method  = $this->http_method;
        $matches = array_map(function ($path) use ($method) {
            $path = trim(Enterprise::config('property.route.prefix'), '/') . $path;
            if (Str::contains($path, ':')) {
                [$method, $path] = explode(':', $path);
                $method = explode(',', $method);
            }
            return compact('method', 'path');
        }, $this->http_path);
        foreach ($matches as $match) {
            if ($this->matchRequest($match, $request)) {
                return true;
            }
        }
        return false;
    }
}